<template>
  <div class="topic-container">
    <div class="topic-header">
      <button class="back-btn" @click="goBack">← 返回</button>
      <h1 class="topic-title">当前话题：{{ topicName }}</h1>
    </div>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="社区" name="community">
        <div class="scroll-wrapper">
          <div class="content-list">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading-text">加载中...</div>

            <!-- 内容列表 -->
            <div
              class="content-card"
              v-for="item in contents"
              :key="item.itemId"
              @click="!inPreviewMode && goDetail(item)"
            >
              <!-- 更多菜单 -->
              <div class="more-menu-wrapper" @click.stop>
                <el-dropdown @command="(cmd) => handleCommand(cmd, item)">
                  <span class="more-btn">···</span>
                  <template #dropdown>
                    <el-dropdown-item command="report">举报</el-dropdown-item>
                  </template>
                </el-dropdown>
              </div>

              <!-- 用户信息 -->
              <div class="user-info" @click.stop="goUserProfile(item.authorId)">
                <img :src="item.avatar" class="avatar" />
                <span class="username">{{ item.authorName }}</span>
              </div>

              <!-- 内容主体 -->
              <div class="content-main">
                <div class="title-wrapper">
                  <h3 class="title">{{ item.title }}</h3>
                </div>
                <div class="content-text">{{ item.content }}</div>

                <!-- 图片展示 -->
                <div class="image-grid" v-if="item.images?.length" @click.stop>
                  <div
                    v-for="(img, idx) in item.images.slice(0, 3)"
                    :key="idx"
                    class="image-wrapper"
                    @click.stop="previewImage(idx, item.images)"
                  >
                    <img :src="img" class="content-image" />
                    <div
                      v-if="idx === 2 && item.images.length > 3"
                      class="image-count"
                    >
                      共 {{ item.images.length }} 张
                    </div>
                  </div>
                </div>
              </div>

              <!-- 页脚信息 -->
              <div class="content-footer">
                <div class="stats">
                  <span class="stat-item">💬 {{ item.commentCount }}</span>
                  <span class="stat-item">👍 {{ item.likeCount }}</span>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-if="!loading && contents.length === 0" class="empty-text">
              该话题下暂无内容
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="书籍" name="book">
        <template v-if="currentBookId">
          <BookTab
            :book-id="currentBookId"
            embedded-mode
            @back="activeTab = 'community'"
          />
        </template>
        <div v-else class="book-loading-state">
          <!-- 根据不同状态显示内容 -->
          <div v-if="loading" class="loading-tip">
            <i class="el-icon-loading"></i>
            正在加载书籍信息...
          </div>
          <div v-else class="empty-tip">
            <el-empty description="该话题暂未关联书籍" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="showPreview"
      :url-list="previewImages"
      :initial-index="previewIndex"
      @close="closePreview"
    />

    <!-- 举报对话框 -->
    <ReportDialog v-model="showReportDialog" @submit="handleReportSubmit" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getTopicContent, getTopic } from '@/apis/topic'
import ReportDialog from '@/components/ReportDialog.vue'
import { reportTarget } from '@/apis/report'
import BookTab from './BookTab.vue'

const route = useRoute()
const router = useRouter()
const activeTab = ref('community')
const loading = ref(true)
const currentBookId = ref(null)

// 修改 fetchTopic 方法
const fetchTopic = async () => {
  try {
    loading.value = true
    const res = await getTopic(route.params.id)
    if (res.code === '200') {
      currentBookId.value = res.data.bookId || null
      topicName.value = res.data.topicName || '未命名话题' // 新增此行
    } else {
      topicName.value = '话题加载失败'
    }
  } catch (error) {
    topicName.value = '数据获取异常'
  } finally {
    loading.value = false
  }
}

// 内容数据
const contents = ref([])

// 获取话题内容
const fetchTopicContent = async () => {
  try {
    const res = await getTopicContent(route.params.id)
    if (res.code === '200') {
      contents.value = res.data
    } else {
      ElMessage.error(res.message || '获取内容失败')
    }
  } catch (error) {
    ElMessage.error('网络请求失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchTopicContent()
  fetchTopic()
})

// 图片预览功能
const showPreview = ref(false)
const previewImages = ref([])
const previewIndex = ref(0)
const inPreviewMode = ref(false)
const topicName = ref('加载中...') // 初始化加载状态

const previewImage = (index, images) => {
  previewImages.value = images
  previewIndex.value = index
  showPreview.value = true
  inPreviewMode.value = true
}

const closePreview = () => {
  showPreview.value = false
  setTimeout(() => (inPreviewMode.value = false), 100)
}

// 路由跳转
// 修改后的goDetail方法
const goDetail = (item) => {
  // 根据内容类型跳转不同详情页
  const routeConfig = {
    path:
      item.itemType === 1
        ? `/home/dynamic/${item.itemId}`
        : `/home/article/${item.itemId}`,
  }

  router.push(routeConfig)
}

const goUserProfile = (userId) => {
  router.push(`/home/user/${userId}`)
}

// 举报功能
const showReportDialog = ref(false)
const currentReportTarget = ref(null)

const handleCommand = (command, item) => {
  if (command === 'report') {
    currentReportTarget.value = {
      targetId: item.itemId,
      targetType: item.itemType,
    }
    showReportDialog.value = true
  }
}

const handleReportSubmit = async (formData) => {
  try {
    // 组合举报数据（接口要求格式）
    const reportData = {
      targetId: currentReportTarget.value.targetId,
      targetType: currentReportTarget.value.targetType,
      reason: formData.reason, // 假设表单包含reason字段
      description: formData.description, // 假设表单包含description字段
    }

    // 调用接口
    const res = await reportTarget(reportData)

    if (res.code === '200') {
      ElMessage.success({
        message: '举报已提交，我们将尽快处理',
        duration: 3000,
      })
      showReportDialog.value = false
    } else {
      ElMessage.warning(res.message || '举报提交失败，请稍后重试')
    }
  } catch (error) {
    console.error('举报接口错误:', error)
    ElMessage.error({
      message: '网络异常，请检查连接后重试',
      duration: 3000,
    })
  }
}

const goBack = () => router.back()
</script>

<style scoped>
.topic-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}
.topic-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 24px;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.topic-title {
  margin: 0;
  font-size: 15px;
  color: #333;
  font-weight: 600;
}

.back-btn {
  background: none;
  border: none;
  color: #666;
  font-size: 16px;
  cursor: pointer;
  transition: color 0.3s;
}

.back-btn:hover {
  color: #007bff;
}
.content-list {
  display: grid;
  gap: 24px;
}

.content-card {
  position: relative;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s;
}

.content-card:hover {
  transform: translateY(-2px);
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
}

.username {
  font-weight: 600;
  color: #333;
}

.content-main {
  margin-left: 52px;
}

.title {
  font-size: 18px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.content-text {
  color: #555;
  line-height: 1.6;
  margin-bottom: 16px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 三列等宽布局 */
  gap: 12px;
  width: 100%;
  overflow-x: auto; /* 添加横向滚动条以防内容溢出 */
}

.image-wrapper {
  position: relative;
  aspect-ratio: 4/3; /* 保持图片比例 */
}

.content-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.content-image {
  width: 200px;
  height: 120px;
  border-radius: 6px;
  object-fit: cover;
  transition: opacity 0.3s;
}

.content-image:hover {
  opacity: 0.9;
}

.image-count {
  position: absolute;
  right: 8px;
  top: 8px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.content-footer {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end; /* 改为右对齐 */
}

.stats {
  display: flex;
  gap: 24px;
  color: #666;
  align-items: center; /* 确保垂直居中 */
}

/* 添加图标悬停效果 */
.stat-item {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
}

.stat-item:hover {
  background: #f5f5f5;
}
.more-menu-wrapper {
  position: absolute;
  top: 16px;
  right: 16px;
}

.more-btn {
  font-size: 20px;
  color: #999;
  padding: 0 8px;
  cursor: pointer;
  user-select: none;
}

.scroll-wrapper {
  height: 600px; /* 根据实际header高度调整 */
  overflow-y: auto;
  padding-right: 8px;
  position: relative;
}

/* 美化滚动条 */
.scroll-wrapper::-webkit-scrollbar {
  width: 6px;
}
.scroll-wrapper::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 3px;
}
.scroll-wrapper::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 3px;
}
.scroll-wrapper::-webkit-scrollbar-thumb:hover {
  background: #ccc;
}

/* 优化空状态显示 */
.empty-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  text-align: center;
}

.book-loading-state {
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.empty-tip {
  padding: 40px 0;
}
</style>
